package cn.stylefeng.guns.sys.modular.upload.controller;

import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.upload.entity.FileTable;
import cn.stylefeng.guns.sys.modular.upload.servie.UploadService;
import cn.stylefeng.guns.sys.utils.DatesUtils;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static sun.net.www.protocol.http.HttpURLConnection.userAgent;

@RestController
@RequestMapping("/data")
public class UploadController {
    @Value("${web.upload-path}")
    private String uploadPath;
    @Autowired
    UploadService uploadService;

    @PostMapping("/uploadfile")
    public ResponseData uploadFile(MultipartFile file, HttpServletRequest request, String userId, String messageId) {
        try {
            if (file == null) {
                return ResponseData.error("上传附件为空");
            }
            String fileName = file.getOriginalFilename();
            int index = fileName.lastIndexOf(".");
            String fileType = fileName.substring(index);
            String time = LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE);
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String fileNewName = uuid + fileType;
            String nowTime = DatesUtils.getNowString();
            String remark = request.getParameter("remark");
            String filePath = File.separatorChar + userId + File.separatorChar + time + File.separatorChar;
            uploadService.uploadFile(nowTime, uuid, fileType, filePath + fileNewName, userId, remark, fileName, messageId);
            File uploadFile = new File(uploadPath + filePath, fileNewName);
            if (!uploadFile.exists()) {
                File fileUrl = new File(uploadPath + filePath);
                fileUrl.mkdirs();
            }
            file.transferTo(uploadFile);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseData.error("文件上传失败");
        }
        return ResponseData.success("上传文件成功");
    }

    /**
     * 查看详情 显示待下载文件列表
     *
     * @return
     */
    @GetMapping("/selectByList")
    public LayuiPageInfo downLoad(String messageId) {
        IPage<Map<String, Object>> page = uploadService.selectByList(messageId);
        return LayuiPageFactory.createPageInfo(page);
    }

    /*
     * 文件下载接口
     */
    @GetMapping("/downloadFile")
    public void downloadFile(String messageId, HttpServletResponse response) throws IOException {
        HashMap<String, Object> map = new HashMap<>();
        IPage<Map<String, Object>> page = uploadService.selectByList(messageId);
        LayuiPageInfo pageInfo = LayuiPageFactory.createPageInfo(page);
        List data = pageInfo.getData();
        HashMap<String, Object> m = (HashMap<String, Object>) data.get(0);
        String filePath = String.valueOf(m.get("file_path"));
        String file_name = String.valueOf(m.get("file_name"));
        InputStream inStream = new FileInputStream(uploadPath + filePath);
        response.reset();
        if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            file_name = java.net.URLEncoder.encode(file_name, "UTF-8");
        } else {
            // 非IE浏览器的处理：  
            file_name = new String(file_name.getBytes("UTF-8"), "ISO-8859-1");
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("bin");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + file_name + "\"");
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024];
        while (0 != IOUtils.read(inStream, bytes)) {
            IOUtils.write(bytes, outputStream);
        }
        IOUtils.closeQuietly(outputStream);
    }

    /**
     * 查询
     */
    @RequestMapping("/list")
    public List<FileTable> queryFileTableInfo(@RequestParam Integer userId, Integer messageId) {
        return uploadService.queryFileTable(userId, messageId);
    }

}
